import ol from "ol";
// import proj from "ol/proj";
import projzh from "projzh";

// ol=Object.defineProperty(ol,"proj",{})
// ol.proj={}
// ol.proj = proj
const mc2gcj02mc = function (input:any, opt_output:any, opt_dimension:any) {
  var output = projzh.projection.sphericalMercator.inverse(input, opt_output, opt_dimension);
  output = projzh.datum.gcj02.fromWGS84(output, output, opt_dimension);
  return projzh.projection.sphericalMercator.forward(output, output, opt_dimension);
}

const gcj02mc2mc = function (input:any, opt_output:any, opt_dimension:any) {
  var output = projzh.projection.sphericalMercator.inverse(input, opt_output, opt_dimension);
  output = projzh.datum.gcj02.toWGS84(output, output, opt_dimension);
  return projzh.projection.sphericalMercator.forward(output, output, opt_dimension);
}

const gcj02mc2ll = function (input:any, opt_output:any, opt_dimension:any) {
  var output = projzh.projection.sphericalMercator.inverse(input, opt_output, opt_dimension);
  return projzh.datum.gcj02.toWGS84(output, output, opt_dimension);
}

const ll2gcj02mc = function (input:any, opt_output:any, opt_dimension:any) {
  var output = projzh.datum.gcj02.fromWGS84(input, opt_output, opt_dimension);
  return projzh.projection.sphericalMercator.forward(output, output, opt_dimension);
}

var gcj02mc = new ol.proj.Projection({
  code: 'GCJ02MC',
  extent: ol.extent.applyTransform([-180, -90, 180, 90], ll2gcj02mc),
  units: 'm'
});

ol.proj.addProjection(gcj02mc);
ol.proj.addCoordinateTransforms('EPSG:4326', gcj02mc, ll2gcj02mc, gcj02mc2ll);
ol.proj.addCoordinateTransforms('EPSG:3857', gcj02mc, mc2gcj02mc, gcj02mc2mc);

let resolutions = []
for (let i = 0; i < 19; i++) {
  resolutions[i] = Math.pow(2, 18 - i) * 0.5971642833948135;
}

var layer = new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7',
    projection: gcj02mc,
    maxZoom: 18,
    tileGrid: new ol.tilegrid.TileGrid({
      origin: [-20037508.342789244, 20037508.34278071],
      minZoom: 3,
      tileSize: [256, 256],
      extent: ol.proj.transformExtent([-180, -90, 180, 90], 'EPSG:4326', 'GCJ02MC'),
      resolutions: resolutions
    })
  })
})

var map = new ol.Map({
  layers: [layer],
  target: 'map',
  view: new ol.View({
    center: ol.proj.transform([121.4538, 34.465], 'EPSG:4326', 'GCJ02MC'),
    zoom: 7,
    projection: 'GCJ02MC'
  })
});
